﻿#include "Utils.h"

GLuint _getGLSL(GLuint shaderType, std::string shaderPath) {
	GLuint shader = glCreateShader(shaderType);
	FILE* file = fopen(shaderPath.c_str(), "rb");
	if (file == NULL) {
		printf("打开着色器文件时出错。\n");
		exit(-1);
	}
	fseek(file, 0, SEEK_END);
	size_t fileSize = ftell(file);
	fseek(file, 0, SEEK_SET);
	char* codes = new char[fileSize + 1];
	fread(codes, 1, fileSize, file);
	for (size_t i = 0; i < fileSize + 1; i++) {
		if (codes[i] < 0 || i == fileSize) {
			codes[i] = '\0';
			break;
		}
	}
	glShaderSource(shader, 1, (const GLchar**)&codes, NULL);
	glCompileShader(shader);
	GLint success;
	char infoLog[512];
	glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
	if (!success) {
		glGetShaderInfoLog(shader, 512, NULL, infoLog);
		std::cerr << "着色器编译错误: " << infoLog << std::endl;
		return 0;
	}
	delete[] codes;
	fclose(file);
	return shader;
}

GLuint Utils::activateShader(std::string vertexShaderPath, std::string fragmentShaderPath) {
	GLuint vertexShader = _getGLSL(GL_VERTEX_SHADER, vertexShaderPath);
	GLuint fragmentShader = _getGLSL(GL_FRAGMENT_SHADER, fragmentShaderPath);
	GLuint shaderProgram = glCreateProgram();
	glAttachShader(shaderProgram, vertexShader);
	glAttachShader(shaderProgram, fragmentShader);
	glLinkProgram(shaderProgram);
	GLint success;
	char infoLog[512];
	glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
	if (!success) {
		glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
		std::cerr << "着色器程序链接错误: " << infoLog << std::endl;
		return 0;
	}
	glDeleteShader(vertexShader);
	glDeleteShader(fragmentShader);
	return shaderProgram;
}